package com.springboot2.controller;

import com.springboot2.entity.Resource;
import com.springboot2.service.ResourceService;
import com.springboot2.utils.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("resource/")
public class ResourceController {

    @javax.annotation.Resource
    private ResourceService resourceService;

    //增
    @PostMapping("add")
    public Result add(@RequestBody Resource resource){
        resourceService.add(resource);
        return Result.success();
    }
    //删
    @DeleteMapping("del/{id}")
    public Result del(@PathVariable int id){
        resourceService.del(id);
        return Result.success();
    }
    //改
    @PutMapping("update")
    public Result update(@RequestBody Resource resource){
        resourceService.update(resource);
        return Result.success();
    }
    //获取对象
    @GetMapping("findById/{id}")
    public Result findById(@PathVariable int id){
        return Result.success(resourceService.findById(id));
    }
    //获取列表
    @GetMapping("list")
    public Result list(){
        return Result.success(resourceService.findList());
    }
    //分页列表
    @GetMapping("findByPage/{pageNo}/{pageSize}")
    public Result findByPage(@PathVariable int pageNo,@PathVariable int pageSize){
        Map<String,Object> map = new HashMap<>();
        map.put("data",resourceService.findByPage(pageNo,pageSize));
        map.put("total",resourceService.count());
        return Result.success(map);
    }
    //查询条件
    @GetMapping("findByPageParams/{pageNo}/{pageSize}/{name}")
    public Result findByPageParams(@PathVariable int pageNo,@PathVariable int pageSize,@PathVariable String name){
        Map<String,Object> map = new HashMap<>();
        map.put("data",resourceService.findByPageParams(pageNo,pageSize,name));
        map.put("total",resourceService.countParams());
        return Result.success(map);
    }
    //批量删除
    @GetMapping("findIds")
    public Result findAllId(){
        return Result.success(resourceService.findAllId());
    }
    //批量删除
    @DeleteMapping("batch/{ids}")
    @Transactional
    public Result delList(@PathVariable String ids){
        String [] splitIds = ids.split(",");
        for (String splitId: splitIds) {
            resourceService.del(Integer.parseInt(splitId));
        }
        return Result.success();
    }
}
